package com.ithinks.flow.common.utils.protocol.netty.serializable.msgpack;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.net.InetSocketAddress;

/**
 * @Description
 * @ClassName ServerMsgPackEcho
 * @Author MR.LI
 * @date 2020.12.09 18:46
 */
public class ServerMsgPackEcho {
    public static final int PORT = 9999;

    public static void main(String[] args) throws InterruptedException {
        ServerMsgPackEcho serverMsgPackEcho = new ServerMsgPackEcho();
        System.out.println("服务器即将启动");
        serverMsgPackEcho.start();
    }
    public void start() throws InterruptedException {
        final MsgPackServerHandler serverHandler = new MsgPackServerHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(PORT))
                    .childHandler(new ChannelInitializerTmp());
            ChannelFuture future = bootstrap.bind().sync();
            System.out.println("服务器启动完成，等待客户端连接和数据发送");
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    private static class ChannelInitializerTmp extends ChannelInitializer<Channel>{

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535,
                    0,2,0,2));
            channel.pipeline().addLast(new MsgPackDecoder());
            channel.pipeline().addLast(new MsgPackServerHandler());
        }
    }
}
